import dataPreferences from '@ohos.data.preferences';
import { ValueType } from '@ohos.data.ValuesBucket';
import { Context } from '@ohos.abilityAccessCtrl';

// 存储完整的Account信息.当前登录的用户信息
export const AccountInfoKey = "account_info_key";

// 上一次登录的用户信息
export const LastAccountInfoKey = "LastAccountInfoKey";

export const DeviceId = "DeviceId"; // 设备唯一编号

export const UM_Device_Token = "umdevicetoken"; // 友盟Device token 目前没有，设置空

//app启动期间是否申请了通知权限
export const RequestNotifyPermissionKey = "RequestNotifyPermissionKey";


export const PmPublicKey = "abcdabcdabcdabcd";

async function encrypt(value: string): Promise<string> {
  // let encryptValue = await AesCbcCryptor.sharedInstance().encrypt(PmPublicKey,value)
  //   .catch((e)=>{
  //     let err = e as Error;
  //     throw err;
  //   })
  // return encryptValue;
  return value;
}
//
async function decrypt(secureStr: string): Promise<string> {
  // let value = await AesCbcCryptor.sharedInstance().decrypt(PmPublicKey,secureStr)
  //   .catch((e)=>{
  //     let err = e as Error;
  //     throw err;
  //   })
  // return value;
  return secureStr;
}





  const SHARED_KEY: string = "shared";

  export class PreferenceManager {
    //Preference本身做了内存缓存
    static context: Context;

    static async initClass(context: Context): Promise<void> {
      PreferenceManager.context = context;
      if (!PreferenceManager._sharedInstance) {
        PreferenceManager._sharedInstance = new PreferenceManager(SHARED_KEY);
        await PreferenceManager._sharedInstance.init();
        preferenceManager = PreferenceManager._sharedInstance;
      }
    }

    private preference: dataPreferences.Preferences
    private name: string;
    private static _sharedInstance: PreferenceManager;

    public static sharedInstance() {
      return PreferenceManager._sharedInstance;
    }

    //创建实例后,不能直接使用,因为是异步初始化好的.
    //可以使用首屏进行处理,在这里进行所有的初始化操作.
    constructor(name: string) {
      this.name = name;

    }

    private async init() {
      let preferences = await dataPreferences.getPreferences(PreferenceManager.context, this.name);
      this.preference = preferences;
    }

    /**
     * TIPS:
     * 必须调用flush否则不会保存成功.
     * @param key
     * @param object
     */
    async save(key: string, object: ValueType):Promise<void> {
      let objString = object.toString();
      await this.saveString(key,objString);
    }

    remove(key: string) {
      this.preference.deleteSync(key);
      this.preference.flush();
    }

    /**
     * 保存普通对象.
     * @param key
     * @param object
     */
    async saveObj(key: string, object: object):Promise<void> {
      if (object instanceof Map) {
        // throw ryErrorWithCode(RYErrorCode.InvalidInterfaceParam)
      }
      let jsonString = JSON.stringify(object)
      await this.saveString(key,jsonString);
    }

    async saveMap(key: string, map: Map<string, any>):Promise<void> {
      const plainObj = Array.from(map).reduce((acc, [key, value]) => {
        acc[key] = value;
        return acc;
      }, {});
      let jsonString = JSON.stringify(plainObj)
      await this.saveString(key,jsonString)
        .catch((e)=>{
          let err = e as Error;
          throw err;
        })
    }

    // fetch(key: string): string {
    //   return this.fetchString(key);
    // }

    /**
     * 目前所有save都通过string保存.
     * @param key
     * @param object
     */
    async saveString(key: string, object: string):Promise<void> {
      let encryptValue = await encrypt(object);
      this.preference.putSync(key, encryptValue);
      this.preference.flush();
    }

    async fetchString(key: string): Promise<string> {
      let encryptValue =  this.preference.getSync(key, "") as string;
      if(!encryptValue) return "";
      let value = await decrypt(encryptValue);
      return value;
    }

    /**
     * 获取map对象
     * @param key
     * @returns
     */
    async fetchMap(key: string): Promise<Map<string, any> | undefined> {
      let json = await this.fetchString(key);
      if (json) {
        try {
          let obj = JSON.parse(json);
          const map = new Map<string, any>(Object.entries(obj));
          return map;
        } catch (e: unknown) {
          // throw ryErrorWithCode(RYErrorCode.JsonParseError)
        }
      }
      return undefined;
    }

    /**
     * 获取普通对象. 非map
     * @param key
     * @returns
     */
    async fetchObj<T>(key: string): Promise<T | undefined> {
      let json = await this.fetchString(key);
      if (json) {
        try {
          let obj = JSON.parse(json) as T;
          return obj;
        } catch (e: unknown) {
          // throw ryErrorWithCode(RYErrorCode.JsonParseError)
        }
      }
      return undefined;
    }

    async fetchNumber(key: string): Promise<number | null> {
      let val: string = await this.fetchString(key);
      if (val.length == 0) {
        return null;
      }
      let ret = Number.parseInt(val);
      if (Number.isNaN(ret)) {
        return null;
      }
      return ret;
    }

    async fetchBool(key: string,defaultValue:boolean = false): Promise<boolean> {
      let val: string = await this.fetchString(key) as string;
      if (val.length == 0) {
        //没有内容返回 defaultValue.
        return defaultValue;
      }
      if(val === "true") {
        return true;
      }
      else {
        return false;
      }
    }
  }

export let preferenceManager: PreferenceManager = undefined;